package InternetCode.Socket.Exa10;


import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * 通过Socket传输对象数据
 */
public class ServerSocketFrame{

    private ObjectOutputStream writer;
    private ObjectInputStream reader;
    private ServerSocket server;
    private Socket socket;
    private Scanner scanner;

    /**
     * 创建服务器等待连接
     */
    public void getServer() {
        try {
            //创建SeverSocket套接字
            server = new ServerSocket(1978);
            System.out.println("服务器套接字已经创建成功\n");

            while (true) { // 如果套接字是连接状态
                System.out.println("等待客户机的连接......\n");
                //进入监听状态，等待连接
                socket = server.accept();
                //获得客户端输入流
                reader = new ObjectInputStream(socket.getInputStream());
                //获取客户端输出流
                writer = new ObjectOutputStream(socket.getOutputStream());
                getClientInfo(); // 调用getClientInfo()方法
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听客户端发送来消息
     */
    private void getClientInfo() {
        try {
            while (true) {
                Student student= (Student)reader.readObject();
                if (student != null)
                    System.out.println("接收到客户机发送的信息：学生编号" +student.getId()+"学生姓名:"+student.getName()+ "\n"); // 获得客户端信息
            }
        } catch (Exception e) {
            System.out.println("客户端已退出。\n"); // 输出异常信息
        } finally {
            try {
                if (reader != null) {

                    reader.close();// 关闭流

                }
                if (socket != null) {
                    socket.close(); // 关闭套接字
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向客户端发送消息
     */
    private void sendInfoToClient(){
        while(true){
            scanner=new Scanner(System.in);
            System.out.println("请输入要发送的消息:");
            String id=scanner.nextLine();
            String name=scanner.nextLine();
            if(id.equals("quit")){
                break;
            }
            try{
                writer.writeObject(new Student(id,name));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) { // 主方法
        ServerSocketFrame frame = new ServerSocketFrame(); // 创建本类对象
        //此线程用于监听接收消息
        new Thread(new Runnable() {
            @Override
            public void run() {
                frame.getServer();
            }
        }).start();
        //此线程用发送消息给客户端
        new Thread(new Runnable() {
            @Override
            public void run() {
                frame.sendInfoToClient();
            }
        }).start();
    }
    
}
